import React, {useEffect, useState} from 'react'
import {Button, Card, Row, Col, message} from 'antd'
import {history} from 'umi'
import moment from 'moment'
import {ArrowDownOutlined} from '@ant-design/icons'
import AdvancedSearchFrom from '@/components/SearchForm/advancedSearchFrom'
import CustomTable from '@/components/Table'
import page from '../../page.less'
import styles from '../../styles.less'
import {getList, getAllInfor} from '@/service/fiance/index'
import {getDict} from '@/service/common/dict'
import {downloadDocumentUrl} from '@/service/common/download'

const formItemLayout = {
	labelCol: {flex: '100px'},
	wrapperCol: {flex: '1'},
}

function AccountsReceivable() {
	const [dict, setDict] = useState({
		order_finance_pay_status: [],
		order_rent_type: [],
		order_payment_method: [],
		order_finance_collection_type: [],
	}) // 字典值
	const [action, setAction] = useState(1)
	// 根据状态判断退款按钮显示隐藏
	const butList = (record: any) => {
		if (
			(record.payStatus === '1' || record.payStatus === '2') &&
			record.isSett === 0
		) {
			return (
				<>
					<Button
						type="link"
						onClick={() =>
							history.push(
								`/finance/accountsReceivable/details?id=${record.id}`,
							)
						}>
						查看
					</Button>
					<Button
						type="link"
						onClick={() =>
							history.push(
								`/finance/accountsReceivable/info?id=${record.id}`,
							)
						}>
						收款
					</Button>
				</>
			)
		}

		return (
			<>
				<Button
					type="link"
					onClick={() =>
						history.push(
							`/finance/accountsReceivable/details?id=${record.id}`,
						)
					}>
					查看
				</Button>
			</>
		)
	}
	// 搜索条件
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '订单编号',
					name: 'orderCarNo',
					key: 'orderCarNo',
					placeholder: '请输入订单编号',
				},
				{
					type: 'input',
					key: 'driverName',
					name: 'driverName',
					label: '司机名称',
					placeholder: '请输入司机名称',
				},
				{
					type: 'select',
					key: 'payStatus',
					name: 'payStatus',
					label: '支付状态',
					keys: 'dictKey',
					title: 'dictValue',
					items: dict?.order_finance_pay_status,
				},
				{
					type: 'select',
					key: 'rentType',
					name: 'rentType',
					label: '订单类型',
					keys: 'dictKey',
					title: 'dictValue',
					items: dict?.order_rent_type,
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'input',
					label: '车牌号',
					name: 'plateNo',
					key: 'plateNo',
					placeholder: '请输入车牌号',
				},
				{
					type: 'dateRange',
					key: 'receivableTime',
					name: 'receivableTime',
					label: '应收时间',
					placeholder: '应收时间范围',
				},
				{
					type: 'dateRange',
					key: 'paidTime',
					name: 'paidTime',
					label: '实收时间',
					placeholder: '实收时间范围',
					render: (text: any, record: any) => (
						<>{record?.payStatus === '1' ? '' : <>{text}</>}</>
					),
				},
				{
					type: 'select',
					key: 'paymentMethod',
					name: 'paymentMethod',
					label: '付款方式',
					keys: 'dictKey',
					title: 'dictValue',
					items: dict?.order_payment_method,
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'select',
					key: 'collectionType',
					name: 'collectionType',
					label: '收款类型',
					keys: 'dictKey',
					title: 'dictValue',
					items: dict?.order_finance_collection_type,
				},
				{
					type: 'input',
					key: 'receivableNo',
					name: 'receivableNo',
					label: '应收单编号',
				},
				{key: '1'},
				{key: '2'},
			],
		},
	]
	const columns = [
		{
			title: '应收单编号',
			dataIndex: 'receivableNo',
			align: 'center',
			key: 'receivableNo',
			width: 250,
		},
		{
			title: '订单编号',
			dataIndex: 'orderCarNo',
			align: 'center',
			key: 'orderCarNo',
			width: 300,
		},
		{
			title: '司机名称',
			dataIndex: 'driverName',
			align: 'center',
			key: 'driverName',
			width: 100,
		},
		{
			title: '支付状态',
			dataIndex: 'payStatusname',
			align: 'center',
			key: 'payStatusname',
			width: 100,
		},
		{
			title: '收款类型',
			dataIndex: 'collectionTypename',
			align: 'center',
			key: 'collectionTypename',
			width: 100,
		},
		{
			title: '账单期数',
			dataIndex: 'stage',
			align: 'center',
			key: 'stage',
			width: 100,
			render: (text: any) => <>{text === 0 ? '--' : text}</>,
		},
		{
			title: '应收日期',
			dataIndex: 'receivableTime',
			align: 'center',
			key: 'receivableTime',
			width: 250,
		},
		{
			title: '应收金额',
			dataIndex: 'receivableAmount',
			align: 'center',
			key: 'receivableAmount',
			width: 100,
			render: (text: any) => <>{text === 0 ? '0' : text}</>,
		},
		{
			title: '费用减免金额',
			dataIndex: 'abatementAmount',
			align: 'center',
			key: 'abatementAmount',
			width: 100,
			render: (text: any) => <>{text === 0 ? '0' : text}</>,
		},
		{
			title: '免租金额',
			dataIndex: 'exemptionAmount',
			align: 'center',
			key: 'exemptionAmount',
			width: 100,
			render: (text: any) => <>{text === 0 ? '0' : text}</>,
		},
		{
			title: '已收金额',
			dataIndex: 'receivedAmount',
			align: 'center',
			key: 'receivedAmount',
			width: 100,
			render: (text: any) => <>{text === 0 ? '0' : text}</>,
		},
		{
			title: '待收金额',
			dataIndex: 'uncollectedAmount',
			align: 'center',
			key: 'uncollectedAmount',
			width: 100,
			render: (text: any) => <>{text === 0 ? '0' : text}</>,
		},
		{
			title: '车牌号',
			dataIndex: 'plateNo',
			align: 'center',
			key: 'plateNo',
			width: 150,
		},
		{
			title: '订单类型',
			dataIndex: 'rentTypename',
			align: 'center',
			key: 'rentTypename',
			width: 150,
		},
		{
			title: '所属公司',
			dataIndex: 'companyName',
			align: 'center',
			key: 'companyName',
			width: 150,
		},
		{
			title: '付款方式',
			dataIndex: 'paymentMethodname',
			align: 'center',
			key: 'paymentMethodname',
			width: 100,
		},
		{
			title: '实收时间',
			dataIndex: 'collectionTime',
			align: 'center',
			key: 'collectionTime',
			width: 250,
		},
		{
			title: '逾期天数',
			dataIndex: 'overdue',
			align: 'center',
			key: 'overdue',
			width: 100,
			render: (text: any) => <>{text === 0 ? '0' : text}</>,
		},
		{
			title: '操作',
			dataIndex: '',
			width: 160,
			fixed: 'right',
			render: (_text: any, record: any) => butList(record),
		},
	]
	// 搜索条件
	const [formValue, setFormValue] = useState({})
	// 应收账款总金额
	const [receivableNum, setReceivableNum] = useState(0)
	// 待收账款总金额
	const [uncollectedNum, setUncollectedNum] = useState(0)
	// 已收账款总金额
	const [receivedNum, setReceivedNum] = useState(0)
	// 费用减免总金额
	const [abatementNum, setAbatementNum] = useState(0)
	// 免租总金额
	const [exemptionNum, setExemptionNum] = useState(0)
	// 列表数据
	const [tableList, setTableList] = useState([])
	// 分页数据
	const [total, setTotal] = useState([])
	const [formItem, setFormItem] = useState({})

	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [currentPage, setCurrentPage] = useState({current: 1})
	// 日期字符串转成时间戳
	// 例如var date = '2015-03-05 17:59:00.0';
	function dateStrChangeTimeTamp(dateStr: string) {
		let data = dateStr
		data = data?.substring(0, 19)
		data = data?.replace(/-/g, '/')
		const timeTamp = new Date(data).getTime()
		return timeTamp
	}

	// 获取账单列表
	const getTableList = (data: any, info: any) => {
		getList({...info, ...data}).then((res) => {
			if (res?.success) {
				// 后端不返回逾期天数，需要计算 实收时间减去应收时间，四舍五入保留整数
				if (res?.data?.records) {
					const values = [...res.data.records]
					values.forEach((item: any) => {
						const startTime: number = dateStrChangeTimeTamp(
							item.receivableTime,
						)
						const endTime: number = dateStrChangeTimeTamp(
							item.collectionTime,
						)
						if (endTime - startTime > 0) {
							// eslint-disable-next-line no-param-reassign
							item.overdue = (
								(endTime - startTime) /
								(1000 * 3600 * 24)
							).toFixed()
						} else {
							// eslint-disable-next-line no-param-reassign
							item.overdue = 0
						}
					})
					const list: any = [...values]
					setTableList(list)
					setTotal(res?.data?.total)
				}
			}
		})
	}
	// 获取汇总账单
	const getAllBill = () => {
		getAllInfor({}).then((res) => {
			if (res?.success) {
				setReceivableNum(res?.data?.receivableNum)
				setUncollectedNum(res?.data?.uncollectedNum)
				setReceivedNum(res?.data?.receivedNum)
				setAbatementNum(res?.data?.abatementNum)
				setExemptionNum(res?.data?.exemptionNum)
			}
		})
	}
	//  搜索
	const onFinish = (values: any) => {
		const info = {...values}
		// 应收开始-结束时间
		if (values?.receivableTime) {
			info.receivableStartTime = moment(values?.receivableTime[0]).format(
				'YYYY-MM-DD HH:mm:ss',
			)
			info.receivableEndTime = moment(values?.receivableTime[1]).format(
				'YYYY-MM-DD HH:mm:ss',
			)
		}
		// 实收开始-结束时间
		if (values?.paidTime) {
			info.collectionStartTime = moment(values?.paidTime[0]).format(
				'YYYY-MM-DD HH:mm:ss',
			)
			info.collectionEndTime = moment(values?.paidTime[1]).format(
				'YYYY-MM-DD HH:mm:ss',
			)
		}
		info.pageType = action
		// 删除多余字段
		delete info?.receivableTime
		delete info?.paidTime
		setFormItem(info)
		const page1 = {
			current: 1,
			size: 10,
		}
		getTableList(info, page1)
		setCurrentPage({current: 1})
	}
	// 清空
	const onReset = () => {
		const page1 = {
			current: 1,
			size: 10,
		}
		setFormItem({})
		getTableList({pageType: action}, page1)
		setFormValue({})
		setCurrentPage({current: 1})
	}
	useEffect(() => {
		getTableList({pageType: 1}, params)
		getAllBill()
	}, [])
	// 获取字典
	useEffect(() => {
		getDict(
			{
				dictKeys: [
					'order_finance_pay_status', // 支付状态
					'order_rent_type', // 订单列类型
					'order_payment_method', // 付款方式
					'order_finance_collection_type', // 收款类型
				],
			},
			(res: any) => {
				setDict(res)
			},
		)
	}, [])
	// 切换统计类型
	const setActions = (info: number) => {
		setAction(info)
		const data = {
			pageType: info,
		}
		setCurrentPage({current: 1})
		const pages = {
			current: 1,
			size: 10,
		}
		getTableList(data, pages)
	}
	return (
		<>
			<div className={`${page.card} ${page.page}`}>
				<div className={`${styles.statistics}`}>
					<Row gutter={24}>
						<Col span={3} style={{maxWidth:'100%'}}>
							<Card
								hoverable
								className={action === 1 && styles.action}
								onClick={() => {
									setFormItem({})
									setActions(1)
									setFormValue({})
								}}>
								<div style={{display: 'flex'}}>
									<Card.Meta
										title="应收账款总金额"
										description={`￥${receivableNum}`}
									/>
								</div>
							</Card>
						</Col>
						<Col span={3} style={{maxWidth:'100%'}}>
							<Card
								hoverable
								className={action === 2 && styles.action}
								onClick={() => {
									setFormItem({})
									setActions(2)
									setFormValue({})
								}}>
								<div style={{display: 'flex'}}>
									<Card.Meta
										title="待收账款总金额"
										description={`￥${uncollectedNum}`}
									/>
								</div>
							</Card>
						</Col>
						<Col span={3} style={{maxWidth:'100%'}}>
							<Card
								hoverable
								className={action === 3 && styles.action}
								onClick={() => {
									setFormItem({})
									setActions(3)
									setFormValue({})
								}}>
								<div style={{display: 'flex'}}>
									<Card.Meta
										title="已收账款总金额"
										description={`￥${receivedNum}`}
									/>
								</div>
							</Card>
						</Col>
						<Col span={3} style={{maxWidth:'100%'}}>
							<Card
								hoverable
								className={action === 4 && styles.action}
								onClick={() => {
									setFormItem({})
									setActions(4)
									setFormValue({})
								}}>
								<div style={{display: 'flex'}}>
									<Card.Meta
										title="费用减免总金额"
										description={`￥${abatementNum}`}
									/>
								</div>
							</Card>
						</Col>
						<Col span={3} style={{maxWidth:'100%'}}>
							<Card
								hoverable
								className={action === 5 && styles.action}
								onClick={() => {
									setFormItem({})
									setActions(5)
									setFormValue({})
								}}>
								<div style={{display: 'flex'}}>
									<Card.Meta
										title="免租总金额"
										description={`￥${exemptionNum}`}
									/>
								</div>
							</Card>
						</Col>
					</Row>
				</div>
			</div>
			<div className={`${page.card} ${page.page} searchFrom`}>
				<AdvancedSearchFrom
					formLayout={formItemLayout}
					onFinish={onFinish}
					onReset={onReset}
					formItems={formItems}
					rows={3}
					values={formValue}
				/>
				<div className={page.list}>
					<Button
						icon={<ArrowDownOutlined />}
						style={{color: '#9A59FF', borderColor: '#9A59FF'}}
						ghost
						size="small"
						onClick={() => {
							downloadDocumentUrl({
								resourceId: '151',
								queryDesc: '应收账单列表导出,resourceId:151',
								queryParam: {...formItem,...{pageType:action}},
							})
						}}>
						导出
					</Button>
					<CustomTable
						pagination
						total={total}
						params={currentPage}
						callback={(pagination: any) => {
							setParams(pagination)
							getTableList(
								{...formItem, pageType: action},
								pagination,
							)
							const data = {
								current: pagination?.current,
							}
							setCurrentPage(data)
						}}
						columns={columns}
						dataSource={tableList}
					/>
				</div>
			</div>
		</>
	)
}

export default AccountsReceivable
